import pytest
import requests
from datetime import datetime

# 定义全局变量
test_results = {
    "start_time": None,
    "end_time": None,
    "total_cases": 0,
    "failed_cases": 0
}

# 企业微信地址
WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=209e9bbf-35ff-4a0f-bbed-fb92eefb4247"


# 发送到企业微信
def send_to_wechat(content):
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": "markdown",
        "markdown": {
            "content": content
        }
    }
    response = requests.post(WEBHOOK_URL, json=data, headers=headers)
    if response.status_code == 200:
        print('消息发送成功')
    else:
        print(f'消息发送失败：{response.text}')


# 使用hook函数为测试用例执行前后注入自定义逻辑，比如统计数据和推送结果
@pytest.hookimpl(tryfirst=True)
def pytest_sessionstart(session):
    """测试会话开始时记录开始时间"""
    test_results["start_time"] = datetime.now()


@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
    """测试会话结束时记录结束时间"""
    test_results["end_time"] = datetime.now()


@pytest.hookimpl(tryfirst=True)
def pytest_runtest_logreport(report):
    """记录测试用例的总数和失败数"""
    if report.when == "call":  # 确保只统计用例执行阶段
        test_results["total_cases"] += 1
        if report.failed:
            test_results["failed_cases"] += 1


@pytest.hookimpl(trylast=True)
def pytest_terminal_summary(terminalreporter, exitstatus):
    """终端输出自定义统计信息并发送到企业微信"""
    start_time = test_results["start_time"]  # 测试开始时间
    end_time = test_results["end_time"]  # 测试结束时间
    total_cases = test_results["total_cases"]  # 测试用例总数
    failed_cases = test_results["failed_cases"]  # 失败次数
    duration = (end_time - start_time).total_seconds() if end_time and start_time else 0  # 总耗时
    failure_rate = (failed_cases / total_cases * 100) if total_cases > 0 else 0  # 失败率

    # 构造测试结果内容
    message = f"""
### 测试执行完成 🎉
- **执行开始时间**: {start_time}
- **执行结束时间**: {end_time}
- **总耗时**: {duration:.2f} 秒
- **测试用例总数**: <font color="green">{total_cases}</font>
- **失败次数**: <font color="red">{failed_cases}</font>
- **失败率**: {failure_rate:.2f}%
    """
    print(message)

    # 发送到企业微信
    send_to_wechat(message)
